package com.siwei.infoextract.wrapper.parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;

import javax.swing.text.html.parser.ParserDelegator;

import com.siwei.infoextract.SystemConfig;

public class DomConverter {
	private InputStream input = null;
		
	public DomConverter(InputStream is) {
		input = is;
	}
	
	public DomConverter(String html) {
		this(new StringBufferInputStream(html));
	}

	public DomNode GenerateDomTree() throws IOException {
		return GenerateDomTree(null);
	}
	
	public DomNode GenerateDomTree(String encoding) throws IOException {
		if (input == null) {
			throw new IllegalArgumentException("Cannot read contents from current stream.");
		}

		ParserDelegator delegator = null;
		InternalConverter process = null;
		InputStreamReader reader = null;

		try {
			delegator = new ParserDelegator();
			process = new InternalConverter();
			if (encoding != null) {
				reader = new InputStreamReader(input, encoding);
			} else {
				reader = new InputStreamReader(input, SystemConfig.getValue(SystemConfig.DEFAULT_ENCODING_KEY));
			}

			delegator.parse(reader, process, true);

			return process.GetDomTreeRoot();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
